<?php 
session_start();
if (isset($_POST['id']) && isset($_SESSION['openid'])){
    include_once("../c/config.php");
    require_once "../jssdk.php";
    $id=$_POST['id'];
    $openid=$_SESSION['openid'];
    
    
    $mysqli = new mysqli($dbhost, $dbuser, $dbpwd, $dbName);
    if (!$mysqli->set_charset("utf8")) {printf("Error loading character set utf8: %s\n", $mysqliTwo->error);}
    
    $query=$mysqli->query("select id from ucard where openid='".$openid."' limit 0, 1");
    if($query->num_rows>0){
        echo json_encode(array('s'=>'has'));
        exit;
    }
    
    
    
    $mysqli->query("insert into log(openid,createtime) values('".$openid."','".date("Y-m-d H:i:s")."')  ");
    $query=$mysqli->query("select id from log where openid='".$openid."' order by id desc limit 0, 1");
    $getLog=$query->fetch_array();
    $LogId=$getLog['id'];
    $query=$mysqli->query("select name from chi where id='".$LogId."' limit 0, 1");
    
    $code= rand(1,999);
    if($query->num_rows>0){
        $chiInfo=$query->fetch_array();
        $code='H'.$chiInfo['name'];
    }

    $sign='';
    function httpGet($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    
    $jssdk = new JSSDK($appId, $secret);
    $acToken=$jssdk->getAccessToken();
    $data = json_decode(file_get_contents("/var/www/hisense-card/juan.json"));
    if ($data->expire_time < time()) {
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$acToken.'&type=wx_card';
        $res = json_decode(httpGet($url));
        $api_ticket = $res->ticket;
        if ($api_ticket) {
            $data->expire_time = time() + 600;
            $data->ticket = $api_ticket;
            $fp = fopen("/var/www/hisense-card/juan.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $api_ticket = $data->ticket;
    }
    class Signature{
        function __construct(){
            $this->data = array();
        }
        function add_data($str){
            array_push($this->data, (string)$str);
        }
        function get_signature(){
            sort( $this->data, SORT_STRING );
            return sha1( implode( $this->data ) );
        }
    };
    
    $timestamp=time();
    $signature = new Signature();
    $signature->add_data($api_ticket);
    $signature->add_data($timestamp);
    $signature->add_data($cardId);
    $signature->add_data($code);
    $signature->add_data($openid);
    $sign=$signature->get_signature();
    
    echo json_encode(array('s'=>'go','c'=>array('cid'=>$cardId, 'code'=>$code, 'timestamp'=>$timestamp,'sign'=>$sign)));  
    
}


